package com.mingqijia.gassafety.authority.vcc.oauth;

import com.mingqijia.gassafety.authority.vcc.provider.VccOauthProvider;
import com.mingqijia.gassafety.authority.vcc.valueobject.VccUserVO;
import com.mingqijia.gassafety.shared.constant.Constants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 管理员用户详情获取
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年07月25日 12:16
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class VccUserDetailsServiceImpl implements UserDetailsService {

    private final VccOauthProvider vccProvider;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (ObjectUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        VccUserVO userDetails = null;
        String[] items = username.split(Constants.STR_SHARP);
        switch (items[0]) {
            case Constants.STR_CODE:
                String clientId = null;
                if (items.length > 2){
                    clientId = items[2];
                }
                log.info("clientId:{}",clientId);
                userDetails = vccProvider.genTokenByCode(items[1],clientId);
                userDetails.setLoginType(Constants.STR_CODE);
                break;
            case Constants.STR_TOKEN:
//                userDetails = new VccUserVO();
//                userDetails.setPhone("13800000001");
                userDetails = vccProvider.genH5TokenByToken(items[1]);
                userDetails.setLoginType(Constants.STR_TOKEN);
                break;
            case Constants.STR_SECRET:
                userDetails = new VccUserVO();
                userDetails.setUsername(items[1]);
                userDetails.setPassword(items[2]);
                userDetails.setLoginType(Constants.STR_SECRET);
                break;
            default:
                break;
        }
        return userDetails;
    }
}
